package com.southwind.dao;

import com.southwind.entity.User;
import com.southwind.utils.JdbcTools;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 传统的开发方式：
 * 1.接口定义业务方法。
 * 2.实现类实现业务方法。
 * 3.实例化实现类对象来完成业务操作。
 * Created by chenhs on 2018/6/26.
 */
public class UserDaoImpl implements UserDAO {
    @Override
    public User get(int id) {
        Connection conn = null;
        String sql = "select * from t_user where id = ?";
        PreparedStatement pstmt = null;
        ResultSet rs = null;

        try {
            conn = JdbcTools.getConnection();
            pstmt = conn.prepareStatement(sql);
            pstmt.setInt(1, id);
            rs = pstmt.executeQuery();
            if (rs.next()) {
                int sid = rs.getInt(1);
                String name = rs.getString(2);
                User user = new User(sid, name);
                return user;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcTools.close(conn, pstmt, rs);
        }
        return null;
    }


    public static void main(String[] args) {
        UserDAO userDAO = new UserDaoImpl();
        User user = userDAO.get(1);
        System.out.println(user);
    }
}
